package com.sgb.merchant.viewmodel;

import android.app.Activity;
import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.alibaba.android.arouter.launcher.ARouter;
import com.sgb.link.api.CommonCallback;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.MainEvent;
import com.sgb.link.entity.UserInfo;
import com.sgb.link.entity.merchant.DynamicListEntity;
import com.sgb.link.entity.merchant.IndustryCategoryEntity;
import com.sgb.link.entity.merchant.IndustryDetailEntity;
import com.sgb.link.entity.merchant.IndustryListEntity;
import com.sgb.link.entity.merchant.InvestmentDetailEntity;
import com.sgb.link.router.PathMerchant;
import com.sgb.link.utils.AddressHelper;
import com.sgb.merchant.api.MerchantsNet;
import com.sgb.merchant.api.MerchantsService;
import com.sgb.merchant.view.activity.EditDynamicActivity;
import com.sgb.net.entity.ListResponse;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseViewModel;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.MToast;
import com.swgk.core.view.areapopup.AddressEntity;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author: 王彬臣
 * @date: 2021/10/13
 * @Description: 产业园区ViewModel
 */
public class IndustryViewModel extends BaseViewModel {
    public MutableLiveData<ListResponse<List<IndustryListEntity>>> ldData = new MutableLiveData<>();
    public MutableLiveData<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>> liveDataCityList = new MutableLiveData<>();
    public MutableLiveData<List<IndustryCategoryEntity>> ldLeve = new MutableLiveData<>();
    public MutableLiveData<List<IndustryCategoryEntity>> ldGroup = new MutableLiveData<>();
    public MutableLiveData<List<IndustryCategoryEntity>> ldType = new MutableLiveData<>();
    public MutableLiveData<Integer> ldState = new MutableLiveData<>();
    public MutableLiveData<ListResponse<List<DynamicListEntity>>> ldDynamic = new MutableLiveData<>();
    public MutableLiveData<IndustryDetailEntity> ldInfo = new MutableLiveData<>();
    public MutableLiveData<UserInfo> ldUserInfo = new MutableLiveData<>();
    public MutableLiveData<BaseEntity> ldResult = new MutableLiveData<>();
    public MutableLiveData<Boolean> ldDoResult = new MutableLiveData<>();
    public MutableLiveData<Boolean> ldStatus = new MutableLiveData<>();
    public MutableLiveData<Boolean> ldDel = new MutableLiveData<>();


    public int pageNum = 1;
    public int dynamicPage = 1;

    public IndustryViewModel(@NonNull @NotNull Application application) {
        super(application);
    }

    /**
     * 首页产业园区列表
     *
     * @param isLoadMore
     * @param map
     */
    public void getInvestmentData(boolean isLoadMore, Map<String, Object> map) {
        pageNum = isLoadMore ? pageNum + 1 : 1;
        map.put("page", pageNum);
        map.put("limit", 20);
        MerchantsNet.getInstance().getService().getParksList(map).enqueue(new ICallBack<BaseEntity<ListResponse<List<IndustryListEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<IndustryListEntity>>> data) {
                if (data.isSuccess()) {
                    ldData.postValue(data.getData());
                }
            }
        });
    }

    /**
     * 我的产业园区列表
     *
     * @param isLoadMore
     * @param map
     */
    public void getSelfInvestmentData(boolean isLoadMore, Map<String, Object> map) {
        pageNum = isLoadMore ? pageNum + 1 : 1;
        map.put("page", pageNum);
        map.put("limit", 20);
        MerchantsNet.getInstance().getService().getSelfParksList(map).enqueue(new ICallBack<BaseEntity<ListResponse<List<IndustryListEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<IndustryListEntity>>> data) {
                if (data.isSuccess()) {
                    ldData.postValue(data.getData());
                }
            }
        });
    }

    /**
     * 获取服务城市
     */
    public void getServiceCity() {
        AddressHelper.getInstance().getAllArea(new AddressHelper.CallBack() {
            @Override
            public void initialData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
                DialogHelper.dismissProgressDialog();
                if (data != null && data.size() > 0) {
                    liveDataCityList.postValue(data);
                }
            }

            @Override
            public void threeData(List<AddressEntity> provinceList, List<List<AddressEntity>> cityList, List<List<List<AddressEntity>>> districtList) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getType() {
        MerchantsNet.getInstance().getService().getParkTypes().enqueue(new ICallBack<BaseEntity<List<IndustryCategoryEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<IndustryCategoryEntity>> data) {
                if (data.isSuccess()) {
                    ldType.postValue(data.getData());
                }
            }
        });
    }

    public void getLevel() {
        MerchantsNet.getInstance().getService().getParkLevels().enqueue(new ICallBack<BaseEntity<List<IndustryCategoryEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<IndustryCategoryEntity>> data) {
                if (data.isSuccess()) {
                    ldLeve.postValue(data.getData());
                }
            }
        });
    }

    public void getGroup() {
        MerchantsNet.getInstance().getService().getParkClusters().enqueue(new ICallBack<BaseEntity<List<IndustryCategoryEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<IndustryCategoryEntity>> data) {
                if (data.isSuccess()) {
                    ldGroup.postValue(data.getData());
                }
            }
        });
    }


    /**
     * 获取状态
     *
     * @param no
     */
    public void getState(String no) {
        MerchantsNet.getInstance().getService().getIndustryState(no).enqueue(new ICallBack<BaseEntity<Integer>>() {
            @Override
            public void onSuccess(BaseEntity<Integer> data) {
                if (data.isSuccess()) {
                    ldState.postValue(data.getData());
                }
            }
        });
    }

    /**
     * 获取产业园区详情
     *
     * @param no
     */

    public void getDetail(String no) {
        MerchantsNet.getInstance().getService().getParksDetail(no).enqueue(new CommonCallback<BaseEntity<IndustryDetailEntity>>(false) {
            @Override
            public void response(BaseEntity<IndustryDetailEntity> data) {
                if (data.isSuccess()) {
                    ldInfo.postValue(data.getData());
                }
            }

            @Override
            protected void failure(Throwable t) {

            }

            @Override
            public void onFailureWithEntity(BaseEntity entity) {
                super.onFailureWithEntity(entity);
                if (entity.getCode().equals("20000")) {
                    ldState.postValue(1);

                } else if (entity.getCode().equals("20001")) {
                    ldState.postValue(0);
                }
            }
        });
    }

    /**
     * 获取产业园区详情
     *
     * @param no
     */

    public void getSelfDetail(String no) {
        MerchantsNet.getInstance().getService().getParksSelfDetail(no).enqueue(new CommonCallback<BaseEntity<IndustryDetailEntity>>(false) {
            @Override
            public void response(BaseEntity<IndustryDetailEntity> data) {
                if (data.isSuccess()) {
                    ldInfo.postValue(data.getData());
                }
            }

            @Override
            protected void failure(Throwable t) {

            }

            @Override
            public void onFailureWithEntity(BaseEntity entity) {
                super.onFailureWithEntity(entity);
                if (entity.getCode().equals("20000")) {
                    ldState.postValue(1);

                }
            }
        });
    }


    /**
     * 产业园区动态列表
     *
     * @param no
     * @param isLoadMore
     */
    public void getDynamicList(String no, boolean isLoadMore) {
        dynamicPage = isLoadMore ? dynamicPage + 1 : 1;
        Map<String, Object> map = new HashMap<>();
        map.put("page", dynamicPage);
        map.put("limit", 20);
        map.put("industrialParkNo", no);
        map.put("orderByColumn","desc");

        MerchantsNet.getInstance().getService().getDynamicList(map).enqueue(new ICallBack<BaseEntity<ListResponse<List<DynamicListEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<DynamicListEntity>>> data) {
                if (data.isSuccess()) {
                    ldDynamic.postValue(data.getData());
                }
            }
        });
    }

    /**
     * 获取交流IM用户信息
     *
     * @param no
     */
    public void getImInfo(String no) {
        MerchantsNet.getInstance().getService().getImInfo(no).enqueue(new Callback<BaseEntity<UserInfo>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserInfo>> call, Response<BaseEntity<UserInfo>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body() != null && response.body().isSuccess() && response.body().getData() != null) {
                    ldUserInfo.postValue(response.body().getData());
                } else {
                    MToast.showToast(getApplication(), response.body().getMsg());
                }
            }


            @Override
            public void onFailure(Call<BaseEntity<UserInfo>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 获取详情页并进行状态判断
     *
     * @param no
     */
    public void getDetailState(Context context, String no, int type) {//0 编辑 1上架 2下架 3删除

        MerchantsNet.getInstance().getService().getIndustryState(no).enqueue(new ICallBack<BaseEntity<Integer>>() {
            @Override
            public void onSuccess(BaseEntity<Integer> data) {
                if (data.isSuccess()) {
                    int status = data.getData();//0已下架 1已删除 2已上架
                    if(status==1){
                        MToast.showToast(context, "当前数据已删除");
                        ldStatus.postValue(true);
                        return;
                    }
                    switch (type) {
                        case 0:
                            if (status != 0) {
                                ldStatus.postValue(false);
                            } else {
                                ARouter.getInstance().build(PathMerchant.ActivityPublishParks).withString(RouterKey.NO, no).withBoolean(RouterKey.BOOLEAN, true).navigation();
                            }
                            break;
                        case 1:
                            if (status != 0) {
                                ldStatus.postValue(false);
                            } else {
                                new RoundDialog.Builder(context)
                                        .title("温馨提示")
                                        .content("确定上架该条信息？")
                                        .cancel("取消")
                                        .confirm("确定")
                                        .cancelable(false)
                                        .confirmCallback(v12 -> {
                                            updateInvestment(no, "1");
                                        }).show();
                            }
                            break;
                        case 2:
                            if (status != 2) {
                                ldStatus.postValue(false);
                            } else {
                                new RoundDialog.Builder(context)
                                        .title("温馨提示")
                                        .content("下架该信息后，前台将不再继续展示，确定下架？")
                                        .cancel("取消")
                                        .confirm("确定")
                                        .cancelable(false)
                                        .confirmCallback(v12 -> {
                                            updateInvestment(no, "0");
                                        }).show();
                            }
                            break;
                        case 3:
                            if (status != 0) {
                                ldStatus.postValue(false);
                            } else {
                                new RoundDialog.Builder(context)
                                        .title("温馨提示")
                                        .content("请问是否确认删除？")
                                        .cancel("取消")
                                        .confirm("确定")
                                        .cancelable(false)
                                        .confirmCallback(v12 -> {
                                            delProject(no);
                                        }).show();
                            }
                            break;
                    }


                }
            }
        });
    }

    /**
     * 获取详情页并进行状态判断
     *
     * @param no
     */
    public void getDetailState(Activity context, String no, int type, IndustryDetailEntity entity) {//0 编辑 1上架 2下架 3删除
        DialogHelper.showProgressDialog(context, "加载中").setCanceledOnTouchOutside(true);
        MerchantsNet.getInstance().getService().getIndustryState(no).enqueue(new ICallBack<BaseEntity<Integer>>() {
            @Override
            public void onSuccess(BaseEntity<Integer> data) {
                if (data.isSuccess()) {
                    int status = data.getData();//0已下架 1已删除 2已上架
                    if(status==1){
                        ldState.postValue(1);
                        return;
                    }
                    switch (type) {
                        case 0:
                            if (status != 0) {
                                ldStatus.postValue(false);
                            } else {
                                ARouter.getInstance().build(PathMerchant.ActivityPublishParks).withString(RouterKey.NO, entity.getNo()+"")
                                        .withBoolean(RouterKey.BOOLEAN, true).navigation(context, 3000);
                            }
                            break;
                        case 1:
                            if (status != 0) {
                                ldStatus.postValue(false);
                            } else {
                                new RoundDialog.Builder(context)
                                        .title("温馨提示")
                                        .content("确定上架该条信息？")
                                        .cancel("取消")
                                        .confirm("确定")
                                        .cancelable(false)
                                        .confirmCallback(v12 -> {
                                            updateInvestment(no, "1");
                                        }).show();
                            }
                            break;
                        case 2:
                            if (status != 2) {
                                ldStatus.postValue(false);
                            } else {
                                new RoundDialog.Builder(context)
                                        .title("温馨提示")
                                        .content("下架该信息后，前台将不再继续展示，确定下架？")
                                        .cancel("取消")
                                        .confirm("确定")
                                        .cancelable(false)
                                        .confirmCallback(v12 -> {
                                            updateInvestment(no, "0");
                                        }).show();
                            }
                            break;
                        case 3:
                            if (status != 0) {
                                ldStatus.postValue(false);
                            } else {
                                new RoundDialog.Builder(context)
                                        .title("温馨提示")
                                        .content("请问是否确认删除？")
                                        .cancel("取消")
                                        .confirm("确定")
                                        .cancelable(false)
                                        .confirmCallback(v12 -> {
                                            delProject(no);
                                        }).show();
                            }
                            break;
                    }


                }
            }
        });
    }

    /**
     * 上架下架操作
     *
     * @param no
     * @param status 0上架 1下架
     */
    public void updateInvestment(String no, String status) {
        MerchantsNet.getInstance().getService().setStatus(no, status).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data.isSuccess()) {
                    ldDoResult.postValue(true);
                }
            }
        });
    }

    public void delProject(String no) {
        MerchantsNet.getInstance().getService().delParks(no).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data.isSuccess()) {
                    MToast.showToast(getApplication(), "删除成功");
                    ldDel.postValue(true);
                }
            }
        });
    }

    public void delParkTrends(String no) {
        MerchantsNet.getInstance().getService().delParkTrends(no).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data.isSuccess()) {
                    MToast.showToast(getApplication(), "删除成功");
                    ldDel.postValue(true);
                }
            }
        });
    }

    public void follow(long no) {
        MerchantsNet.getInstance().getService().follow(no, "FT3").enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body() != null && response.body().isSuccess()) {
                    MToast.showToast(getApplication(), response.body().getMsg());
                    ldResult.postValue(response.body());
                } else {
                    MToast.showToast(getApplication(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void editDemands(EditDynamicActivity context, DynamicListEntity entity) {
        MerchantsNet.getInstance().getService().editParkTrends(entity).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_SELF_INDUSTRY_REFRESH2));
                context.finish();
            }
        });
    }
}
